package com.mp.approvalreq.servlet.other.module;

import com.mp.approvalreq.entity.dto.GeneralRequestDTO;
import com.mp.approvalreq.service.SelectApprovalServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.message.SuccessMsg;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/getMyGeneralRequestFlows")
public class GetMyGeneralRequestFlows extends AbstractServlet {
	
	private static final Logger logger = LoggerFactory.getLogger(GetMyGeneralRequestFlows.class);
	
	private static final String PROJECT_IDS = "projectIds";
	private static final String CONTACTID = "contactId";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			User user = initUser(req);
			String projectIds = initProjectIds(req);
	
			logger.info("输入json:{}, {}", user.getContactId(), projectIds);
			
			SelectApprovalServicePrx selectApprovalService = ServiceUtils.getSelectApprovalServicePrx();
			
			List<GeneralRequestDTO> generalRequestDTOS =  selectApprovalService.getMyGeneralRequestFlows(user, projectIds);
			
			String msg = SuccessMsg.getDefaultMsg(generalRequestDTOS);

			logger.info("返回json:{}", msg);
			
			printJson(resp, msg);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private User initUser(HttpServletRequest req) throws Throwable {
		String contactId = req.getParameter(CONTACTID);
		
		if (StringUtils.isEmpty(contactId)) {
			throw new RpcServerLogicalException(1, "用户id不能为空");
		}
		
		return ServiceUtils.getUserServicePrx().getUserByContactId(Integer.valueOf(contactId));
	}
	
	private String initProjectIds(HttpServletRequest req) {
		
		String projectIds = req.getParameter(PROJECT_IDS);
		
		if (StringUtils.isEmpty(projectIds)) {
			throw new RpcServerLogicalException(1, "工程id不能为空");
		}
		
		return projectIds;
	}
}
